<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\implement;

use lflow\helper\StringHelper;
use lflow\WorkFlowInterceptor;
use lflow\workflow\Execution;

/**
 * 委托代理拦截器
 * 负责查询wf_surrogate表获取委托代理人，并通过addTaskActor设置为参与者
 * 这里是对新创建的任务通过添加参与者进行委托代理(即授权人、代理人都可处理任务)
 * 对于运行中且未处理的待办任务，可调用engine.task().addTaskActor方法
 * {@link ITaskService#addTaskActor(String, String...)}
 *
 * @author Mr.April
 * @since  1.0
 */
class SurrogateInterceptor implements WorkFlowInterceptor
{

    public function intercept(Execution $execution): void
    {
        $engine = $execution->getEngine();
        foreach ($execution->getTasks() as $key => $task) {
            if (empty($task->getActorIds())) continue;
            foreach ($task->getActorIds as $key1 => $actor) {
                if (empty($actor)) continue;
                $agent = $engine->manager()->getSurrogate($actor, $execution->getProcess()->getName());
                if (StringHelper:: isNotEmpty($agent) && !StringHelper::equalsIgnoreCase($agent, $actor)) {
                    $engine->task()->addTaskActor($task->getId(), $agent);
                }
            }
        }
    }
}